package com.crm.service.before_sale.impl;

import com.crm.dao.before_sale.OfferDAO;
import com.crm.dao.before_sale.OfferdetailsDAO;
import com.crm.exception.ServiceException;
import com.crm.pojo.Offer;
import com.crm.pojo.OfferDetail;
import com.crm.service.before_sale.OfferService;
import com.crm.vo.OfferDetailsVO;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.sql.rowset.serial.SerialException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 报价业务层
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OfferServiceimpl implements OfferService {
    @Autowired
    private OfferDAO offerDAO;
    @Autowired
    private OfferdetailsDAO offerdetailsDAO;

    /**
     * 删除报价
     * @param ofId
     * @return
     */
    @Override
    public Result deleteOfferById(Long ofId) {
        try {
            offerDAO.deleteOfferById(ofId);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("Sorry,删除失败！");
        }
    }

    /**
     * 分页展示报价表
     * @param offer
     * @param curpage
     * @param pagesize
     * @param minTotalMoney
     * @param maxTotalMoney
     * @param updateStartTime
     * @param updateEndTime
     * @return
     */
    @Override
    public List<Offer> showOfferList(Offer offer, int curpage, int pagesize, BigDecimal minTotalMoney,
                                     BigDecimal maxTotalMoney, Date updateStartTime, Date updateEndTime) {
        Assert.notNull(offer);
        PageRequest pageRequest = new PageRequest(curpage-1,pagesize, Sort.Direction.DESC,"ofId");
        @SuppressWarnings("unchecked")
        Page<Offer> page = offerDAO.findAll(new Specification<Offer>() {
            @Override
            public Predicate toPredicate(Root<Offer> root, CriteriaQuery<?> argl, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //根据以下条件查询
                //1.报价主题
                if(!StringUtils.isEmpty(offer.getTheme())){
                    list.add(cb.like(root.get("theme").as(String.class),"%" + offer.getTheme() + "%"));
                }
                //2.分类
                if(!StringUtils.isEmpty(offer.getOfType())){
                    list.add(cb.like(root.get("ofType").as(String.class),"%" + offer.getOfType() + "%"));
                }
                //没有被删除
                list.add(cb.notLike(root.get("offerIsDel").as(String.class), "是"));

                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageRequest);
        List<Offer> list = page.getContent();
        return list;
    }

    /**
     * 获取报价的总数量
     * @param offer
     * @param minTotalMoney
     * @param maxTotalMoney
     * @param updateStartTime
     * @param updateEndTime
     * @return
     */
    @Override
    public Long getOfferCount(Offer offer, BigDecimal minTotalMoney, BigDecimal maxTotalMoney, Date updateStartTime, Date updateEndTime) {
        Assert.notNull(offer);
        Long total = offerDAO.count(new Specification<Offer>() {
            @Override
            public Predicate toPredicate(Root<Offer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //根据以下条件查询
                //1.报价主题
                if(!StringUtils.isEmpty(offer.getTheme())){
                    list.add(cb.like(root.get("theme").as(String.class),"%" + offer.getTheme() + "%"));
                }
                //2.分类
                if(!StringUtils.isEmpty(offer.getOfType())){
                    list.add(cb.like(root.get("ofType").as(String.class),"%" + offer.getOfType() + "%"));
                }
                //没有被删除
                list.add(cb.notLike(root.get("offerIsDel").as(String.class), "是"));

                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        return total;
    }

    /**
     * 展示一个报价下的明细列表
     * @param ofId
     * @return
     */
    @Override
    public List<OfferDetailsVO> getOfferDetailsVOList(Long ofId) {
        Offer offer = offerDAO.findOne(ofId);
        return offerDAO.getOfferDetailsVOListByOfferId(offer);
    }


    @Override
    public Result addOffer(BigDecimal allOffer, BigDecimal chanceId, String checkState,
                          BigDecimal clientId, BigDecimal contactId, Date date, String ofNo, String ofType, String theme, BigDecimal userId) {
        try {
            String OFID="";
            //获取当前时间戳
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            String temp = sf.format(new Date());
            //获取7位随机数
            int random=(int) ((Math.random()+1)*1000000);
            String str = "";
            for (int i = 0;i<1;i++){
                str = str+ (char)(Math.random()*26+'A');
            }
            OFID=str + temp + random;
            Offer offer = new Offer();
            offer.setAllOffer(allOffer);
            offer.setChanceId(chanceId);
            offer.setCheckState(checkState);
            offer.setClientId(clientId);
            offer.setDate(new Date());
            offer.setOfferIsDel("否");
            offer.setOfNo(OFID);
            offer.setContactId(contactId);
            offer.setOfType(ofType);
            offer.setTheme(theme);
            offer.setUserId(userId);
            offerDAO.save(offer);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(e);
        }
    }

    /**
     * 添加明细
     * @param offerDetail
     * @param id
     */
    @Override
    public void addOfferDetails(OfferDetail offerDetail, Long id) {
        try {
            Offer o = offerDAO.findOne(id);
            offerDetail.setOffer(o);
            offerDetail.setOfferDetailIsDel("否");
            offerdetailsDAO.save(offerDetail);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }

    }

    /**
     * 根据id获取一条报价明细
     * @param deId
     * @return
     */
    @Override
    public OfferDetailsVO getOneOfferDetail(Long deId) {
        return offerDAO.getOfferDetailById(deId);
    }

    /**
     * 编辑报价
     * @param offer
     * @return
     */
    @Override
    public Result editOffer(Offer offer) {
        try {
            offer.setDate(new Date());
            offerDAO.save(offer);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("Sorry，编辑失败！");
        }
    }

    /**
     * 保存修改的报价明细
     * @param offerDetail
     * @return
     */
    @Override
    public OfferDetail saveOfferDetail(OfferDetail offerDetail) {
        return offerdetailsDAO.save(offerDetail);
    }
}
